package stpmproject.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import stpmproject.controller.viewobject.TeamVO;
import stpmproject.controller.viewobject.UserVO;
import stpmproject.dao.UserPasswordDOMapper;
import stpmproject.dataobject.UserPasswordDO;
import stpmproject.error.BusinessException;
import stpmproject.error.EmBusinessError;
import stpmproject.response.CommonReturnType;
import stpmproject.service.TeamService;
import stpmproject.service.UserService;
import stpmproject.service.model.TeamModel;
import stpmproject.service.model.UserModel;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * encoding: utf-8
 *
 * @Author: kou dui
 * @Date: 2019/4/25 19:58
 * @software: IntelliJ IDEA
 * @file: UserController
 * @description:
 */
//@Controller 表明这个类是一个控制器类，和@RequestMapping来配合使用拦截请求，
// 如果不在method中注明请求的方式，默认是拦截get和post请求
@Controller("user")
@RequestMapping("/user")
@CrossOrigin(allowedHeaders = {"*"},allowCredentials = "true") //springboot前端请求的跨域问题
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserPasswordDOMapper userPasswordDOMapper;

    //通过用户id获取用户的信息
    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getUser(HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        UserVO userVO=new UserVO();
        userVO.setUsername(userModel.getUsername());
        userVO.setRealname(userModel.getRealname());
        userVO.setRole(userModel.getRole());
        return CommonReturnType.create(userVO);
    }
    private UserVO convertFromModel(UserModel userModel){
        UserVO userVO=new UserVO();
        if(userModel==null){
            return null;
        }
        BeanUtils.copyProperties(userModel,userVO);
        return userVO;
    }

    //用户注册接口，注册是需要判断用户的手机和用户名是否已经存在
    @RequestMapping(value = "/register",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType register(@RequestParam(name="telphone") String telphone,
                                     @RequestParam(name="username") String userName,
                                     @RequestParam(name="realname") String realName,
                                     @RequestParam(name="email") String email,
                                     @RequestParam(name="role") String role,
                                     @RequestParam(name="password") String password,
                                     HttpSession session) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        UserModel model=(UserModel) session.getAttribute("LOGIN_USER");
        if(model==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        if(!model.getRole().equals("管理员")){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"只能由管理员添加用户");
        }
        //判断手机号是否已经注册
        UserModel userModel0=userService.getUserByTelphone(telphone);
        if(userModel0!=null){
            throw  new BusinessException(EmBusinessError.TELPHONE_EXITS);
        }
        //判断账号是否已经存在
        UserModel userModel1=userService.getUserByUserName(userName);
        if(userModel1!=null){
            throw  new BusinessException(EmBusinessError.USER_EXIST);
        }
        //用户注册流程，将字段封装成UserModel
        UserModel userModel=new UserModel();
        userModel.setUsername(userName);
        userModel.setRealname(realName);
        userModel.setRole(role);
        userModel.setTelphone(telphone);
        userModel.setEmail(email);
        //此密码没有加密，仅仅用来显示，并不作为传输的对象，并且应当在实际使用中删除
//        userModel.setPassword(password);
        //加密后的密码
        userModel.setEncrptPassword(this.encodeByMd5(password));

        userService.register(userModel);
        return CommonReturnType.create(null);
    }

    //手机登录接口
    @RequestMapping(value = "/loginbyphone",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType loginByPhone(@RequestParam(name = "telphone") String telphone,
                                  @RequestParam(name = "otpcode") String otpCode) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参非空校验
        if(StringUtils.isEmpty(telphone)||StringUtils.isEmpty(telphone)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"用户名或密码不能为空");
        }
        //登录流程
        UserModel userModel=userService.getUserByTelphone(telphone);
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.TELPHONE_NOT_EXIST);
        }
        //判断是否获取了验证码
        String inSessionOtpCode=(String)this.httpServletRequest.getSession().getAttribute(telphone);
        if(inSessionOtpCode==null){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"请先获取验证码");
        }
        //判断验证码是否匹配
        if(!com.alibaba.druid.util.StringUtils.equals(inSessionOtpCode,otpCode)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"输入的验证码错误");
        }
        //将登录成功凭证加到用户登录成功的session内
        this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
        this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
        return CommonReturnType.create(null);
    }

    //用户登录接口
    @RequestMapping(value = "/login",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType login(@RequestParam(name = "username") String username,
                                  @RequestParam(name = "password") String password,
                                  HttpSession session) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参非空校验
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"用户名或密码不能为空");
        }
        //登录流程
        UserModel userModel=userService.validateLogin(username,this.encodeByMd5(password));
        //将登录成功凭证加到用户登录成功的session内
        session.setAttribute("IS_LOGIN",true);
        session.setAttribute("LOGIN_USER",userModel);
        return CommonReturnType.create(null);
    }

    //用户注销接口
    @RequestMapping(value = "/logout",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType logout(HttpSession session) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        session.invalidate();
        return CommonReturnType.create(null);
    }

    //用户获取otp短信验证码接口
    @RequestMapping(value = "/getotp",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name="telphone") String telphone) throws BusinessException {
        //查找手机号码是否存在
        UserModel userModel=userService.getUserByTelphone(telphone);
        if(userModel==null){
            throw new BusinessException(EmBusinessError.TELPHONE_NOT_EXIST);
        }
        //按照一定的规则生成otp验证码
        Random random=new Random();
        int otpRand=random.nextInt(99999);
        otpRand+=10000;
        String otpCode=String.valueOf(otpRand);
        //将otp验证码和用户telphone绑定,使用session将telphone和otpcode绑定
        httpServletRequest.getSession().setAttribute(telphone,otpCode);
        System.out.println("telphone="+telphone+" &otpCode="+otpCode);
        return CommonReturnType.create(null);
        //将otp验证码通过短信通道发送给用户
    }

    //加密密码的方法
    public String encodeByMd5(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5=MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder=new BASE64Encoder();
        String encrpt=base64Encoder.encode(md5.digest(password.getBytes("utf-8")));
        return encrpt;
    }

    //获取用户列表,开启分页功能
    @RequestMapping(value = "/list",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listUser(@RequestParam(name = "page") Integer page,
                                     @RequestParam(name = "limit") Integer limit,
                                     HttpSession session){
        UserModel model=(UserModel) session.getAttribute("LOGIN_USER");
        Page tmpPage=PageHelper.startPage(page,limit);
        List<UserModel> userModelList=userService.listUser();
        List<UserVO> userVOList=userModelList.stream().map(userModel -> {
            UserVO userVO=this.convertFromModel(userModel);
            if(model!=null){
                userVO.setLoginRole(model.getRole());
            }else{
                userVO.setLoginRole(null);
            }
            return userVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(userVOList,tmpPage.getTotal());
    }

    //更新用户信息
    @RequestMapping(value = "/update",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType updateUser(@RequestParam(name = "username_edit") String username,
                                       @RequestParam(name = "realname_edit") String realname,
                                       @RequestParam(name = "role_edit") String role,
                                       HttpSession session) throws BusinessException {
        UserModel model=(UserModel) session.getAttribute("LOGIN_USER");
        if(model==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        UserModel userModel=userService.getUserByUserName(username);
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        if(!model.getRole().equals("管理员")){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"你没有权限编辑用户");
        }
        System.out.println(username);
        userModel.setRealname(realname);
        userModel.setRole(role);
        boolean result=userService.updateUser(userModel);
        if(!result){
            throw new BusinessException(EmBusinessError.USER_UPDATE_FAIL);
        }
        return CommonReturnType.create(null);
    }
    //更新用户信息
    @RequestMapping(value = "/update-realname",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType updateRealname(@RequestParam(name = "username") String userName,
                                           @RequestParam(name = "realname") String realName,
                                           @RequestParam(name = "role") String role,
                                           HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        UserModel userModel1=userService.getUserByUserName(userName);
        userModel1.setRealname(realName);
        userService.updateUser(userModel1);
        return CommonReturnType.create(null);
    }
    //更新用户信息
    @RequestMapping(value = "/update-password",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType updatePassword(@RequestParam(name = "oldPassword") String oldPassword,
                                           @RequestParam(name = "newPassword") String newPassword,
                                           @RequestParam(name = "confirmPassword") String confirmPassword,
                                           @RequestParam(name = "usernameText") String usernameText,
                                           HttpSession session) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        UserModel model=(UserModel) session.getAttribute("LOGIN_USER");
        if(model==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        String encrptPassword=encodeByMd5(oldPassword);
        UserPasswordDO userPasswordDO=userPasswordDOMapper.selectByUserId(model.getId());
        if(!org.apache.commons.lang3.StringUtils.equals(encrptPassword,userPasswordDO.getEncrptPassword())){
            throw new BusinessException(EmBusinessError.PASSWORD_ERROR);
        }
        userPasswordDO.setEncrptPassword(encodeByMd5(newPassword));
        userPasswordDOMapper.updateByPrimaryKeySelective(userPasswordDO);
        return CommonReturnType.create(null);
    }

    //更新删除用户
    @RequestMapping(value = "/delete",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType deleteUser(@RequestParam(name = "id") Integer userId,
                                       HttpSession session) throws BusinessException {
        UserModel model=(UserModel) session.getAttribute("LOGIN_USER");
        if(model==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        UserModel userModel=userService.getUserById(userId);
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        if(!model.getRole().equals("管理员")){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"你没有权限删除用户");
        }
        boolean result=userService.deleteUser(userModel);
        if(!result){
            throw new BusinessException(EmBusinessError.USER_DELETE_FAIL);
        }
        return CommonReturnType.create(null);
    }

    //获取所有的项目经理
    @RequestMapping("/programer")
    @ResponseBody
    public CommonReturnType getProgramer(){
        List<UserModel> userModelList=userService.listProgramer();
        List<UserVO> userVOList=userModelList.stream().map(userModel -> {
            UserVO userVO=new UserVO();
            userVO.setName(userModel.getRealname()+"-"+userModel.getEmail()+"-"+userModel.getRole());
            userVO.setValue(userModel.getUsername());
            return userVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(userVOList);
    }

    //获取所有的开发人员
    @RequestMapping("/developer")
    @ResponseBody
    public CommonReturnType getDeveloper(){
        List<UserModel> userModelList=userService.listDeveloper();
        List<UserVO> userVOList=userModelList.stream().map(userModel -> {
            UserVO userVO=new UserVO();
            userVO.setName(userModel.getRealname()+"-"+userModel.getEmail()+"-"+userModel.getRole());
            userVO.setValue(userModel.getUsername());
            return userVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(userVOList);
    }

    //获取所有的测试人员
    @RequestMapping("/tester")
    @ResponseBody
    public CommonReturnType getTester(){
        List<UserModel> userModelList=userService.listTester();
        List<UserVO> userVOList=userModelList.stream().map(userModel -> {
            UserVO userVO=new UserVO();
            userVO.setName(userModel.getRealname()+"-"+userModel.getEmail()+"-"+userModel.getRole());
            userVO.setValue(userModel.getUsername());
            return userVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(userVOList);
    }

    //获取开发和测试人员
    @RequestMapping("/devtest")
    @ResponseBody
    public CommonReturnType getDeveloperAndTester(){
        //单独获取所有的团队名
        List<Object> list=new ArrayList<>();
        List<TeamModel> teamModelList=teamService.listTeam();
        List<TeamVO> teamVOList=teamModelList.stream().map(teamModel -> {
            TeamVO teamVO=new TeamVO();
            teamVO.setName(teamModel.getTeamProject()+"-"+teamModel.getTeamName()+"-"+teamModel.getTeamStatus());
            teamVO.setValue(teamModel.getTeamName());
            return teamVO;
        }).collect(Collectors.toList());
        list.addAll(teamVOList);
        //单独获取所有开发人员
        List<UserModel> userModelList=userService.listDeveloper();
        List<UserVO> userVOList=userModelList.stream().map(userModel -> {
            UserVO userVO=new UserVO();
            userVO.setName(userModel.getRealname()+"-"+userModel.getEmail()+"-"+userModel.getRole());
            userVO.setValue(userModel.getUsername());
            return userVO;
        }).collect(Collectors.toList());
        list.addAll(userVOList);
        //单独获取所有测试人员
        List<UserModel> userModelList1=userService.listTester();
        List<UserVO> userVOList1=userModelList1.stream().map(userModel -> {
            UserVO userVO=new UserVO();
            userVO.setName(userModel.getRealname()+"-"+userModel.getEmail()+"-"+userModel.getRole());
            userVO.setValue(userModel.getUsername());
            return userVO;
        }).collect(Collectors.toList());
        list.addAll(userVOList1);
        return CommonReturnType.create(list);
    }
}
